package com.shujia.mllib

import org.apache.spark.ml.classification.LogisticRegressionModel
import org.apache.spark.ml.linalg
import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.sql.{DataFrame, SparkSession}

object Demo6ImageUseModel {
  def main(args: Array[String]): Unit = {
    val spark: SparkSession = SparkSession
      .builder()
      .master("local[8]")
      .appName("image")
      .getOrCreate()

    import spark.implicits._
    import org.apache.spark.sql.functions._

    val data: DataFrame = spark
      .read
      .format("image")
      .load("D:\\课件\\机器学习数据\\手写数字\\test2")

    data.printSchema()

    val nameDF: DataFrame = data
      .select($"image.origin" as "origin", $"image.data" as "data")
      .as[(String, Array[Byte])]
      .rdd
      .map {
        case (origin: String, dataArr: Array[Byte]) =>

          //获取图片名
          val name: String = origin.split("/").last


          val arr: Array[Double] = dataArr
            .map(_.toInt)
            //将数据进行归一化，变成0或者1
            .map(i => {
            if (i < 0) {
              1.0
            } else {
              0.0
            }
          })

          //将数据转换成向量
          val vector: linalg.Vector = Vectors.dense(arr)


          (name, vector)
      }
      .toDF("name", "features")


    /**
      * 加载模型
      *
      */


    val model: LogisticRegressionModel = LogisticRegressionModel.load("SPark/data/image_model")

    /**
      *
      * 预测
      */

    val frame: DataFrame = model.transform(nameDF)

    frame.show(1000)
  }

}
